const Router = require("koa-router");
const router = new Router();
const {
  verifyToken,
  getToken,
  authMiddleware,
  getShortToken,
  getLongToken,
} = require("./testTokenTool.js");

let count = 0;
let hasMore = true;

router.get("/testData/getData", async (ctx, next) => {
  let resArr = [];

  if (count <= 30) {
    // 设置是否有更多的数据
    hasMore = true;

    // 增加数据
    for (let i = 0; i < 10; i++) {
      count++;
      resArr.push({
        name: `myname is ${count}`,
        age: count,
        address: `myaddress is ${count}`,
        phone: `myphone is ${count}`,
      });
    }
  } else {
    // 设置是否有更多的数据
    hasMore = false;

    // 重置count
    count = 0;
  }

  ctx.status = 200;
  ctx.body = {
    code: 200,
    data: resArr,
    hasMore: hasMore,
  };
});

// 这里是测试token刷新
router.get("/testData/tokenRefreshTest", authMiddleware, async (ctx, next) => {
  ctx.status = 200;
  ctx.body = {
    code: 200,
    data: "token refresh success test",
  };
});

// 这里是模拟用户登录获取token
router.post("/testData/testGetToken", async (ctx, next) => {
  // 获取用户信息
  const { email, password } = ctx.request.body;

  // 生成token，有可能没有用
  const token = getToken({ email: email });

  // 生成短 token
  const shortToken = getShortToken({ email: email });

  // 生成长 token
  const longToken = getLongToken({ email: email });

  // 返回token
  ctx.status = 200;
  ctx.body = {
    code: 200,
    data: {
      longToken: longToken,
      shortToken: shortToken,
    },
    // data: token,
  };
});

// 测试刷新token，通过长连接来刷新token
router.post("/testData/refreshToken", authMiddleware, async (ctx, next) => {
  // 生成短 token
  const shortToken = getShortToken({ email: ctx.state.user.email });

  // 生成长 token
  const longToken = getLongToken({ email: ctx.state.user.email });

  // 返回token
  console.log("refresh token success", ctx.state.user.email);

  // 长连接成功通过
  ctx.status = 200;
  ctx.body = {
    code: 200,
    data: {
      longToken: longToken,
      shortToken: shortToken,
    },
  };
});

module.exports = router;
